package com.ibangnuo.manage.service.newLandpay;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.Area;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.CommercialTenantDetails;
import com.ibangnuo.framework.domain.Mcc;
import com.ibangnuo.framework.domain.ext.CommercialTenantDetailsExt;
import com.ibangnuo.framework.domain.system.SysDictionary;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.newLandpay.api.NewLandpayClient;
import com.ibangnuo.framework.newLandpay.impl.client.DefaultNewLandpayClient;
import com.ibangnuo.framework.newLandpay.impl.request.*;
import com.ibangnuo.framework.newLandpay.impl.response.*;
import com.ibangnuo.framework.utils.GetImgUrlUtil;
import com.ibangnuo.manage.dao.AreaRepository;
import com.ibangnuo.manage.dao.MccRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.newLandpay.CommercialTenantDetailsRepository;
import com.ibangnuo.manage.service.system.SysDictionaryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: wwy
 * @Date: 2020-01-10 9:56
 */
@Service
public class MerchantsIntoPiecesService {
    private static Logger LOGGER = LoggerFactory.getLogger(MerchantsIntoPiecesService.class);
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CommercialTenantDetailsRepository commercialTenantDetailsRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private SysDictionaryService sysDictionaryService;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private MccRepository mccRepository;
    private String key = "9773BCF5BAC01078C9479E67919157B8";
    private String orgNo = "518";
    /**
     * 商户进件
     * 1.入库 未审核
     * 2.调用接口
     * @param id
     * @return
     */
    public ObjectResult mercRegist(String id) {
        CommercialTenantDetailsExt commercialTenantDetailsExt = this.paramsTransform(id);
        if(commercialTenantDetailsExt ==null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        Map<String, String> contentMap = commercialTenantDetailsExt.getContentMap();
        String contentJson = JSONObject.toJSONString(contentMap);

        String commercialTenantDetailsExtJson = JSONObject.toJSONString(commercialTenantDetailsExt);
        CommercialTenantDetails commercialTenantDetails = JSONObject.parseObject(commercialTenantDetailsExtJson, CommercialTenantDetails.class);
        //commercialTenantDetails.setContent(contentJson);
        commercialTenantDetails.setStatus(0);
        commercialTenantDetailsRepository.save(commercialTenantDetails);
        NewLandMercRegistResponse response = this.mercRegistResult(commercialTenantDetailsExt);
        if(response !=null){
            if(response.isSuccess() && "000000".equals(response.code())){
                commercialTenantDetails.setStatus(4);
                commercialTenantDetails.setMercId(response.getMercId());
                commercialTenantDetails.setStoeId(response.getStoeId());
                commercialTenantDetails.setLogNo(response.getLogNo());
                CommercialTenantDetails save = commercialTenantDetailsRepository.save(commercialTenantDetails);
                //开启线程进行下一步骤操作
                 new Thread(()->{
                    //上传图片
                     this.findUploadImage(save.getCommercialTenantId(),save.getId());
                 }).start();
                return new ObjectResult(CommonCode.SUCCESS,null);
            }
        }
        commercialTenantDetails.setStatus(5);
        commercialTenantDetails.setMessage(JSONObject.toJSONString(response));
        commercialTenantDetailsRepository.save(commercialTenantDetails);
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * 数据库中查询参数并进行转换
     * 1.查询数据库
     * 2.参数进行处理，非空参数全部删除
     * @return
     */
    public CommercialTenantDetailsExt paramsTransform(String id){
        Optional<CommercialTenantDetails> optional = commercialTenantDetailsRepository.findById(id);
        if(!optional.isPresent()){
            return null;
        }
        CommercialTenantDetails commercialTenantDetails = optional.get();
        String jsonString = JSONObject.toJSONString(commercialTenantDetails);
        CommercialTenantDetailsExt commercialTenantDetailsExt = JSONObject.parseObject(jsonString, CommercialTenantDetailsExt.class);
        Map<String,String> contentMap = new HashMap<>();
        Map<String,Object> map = JSONObject.parseObject(jsonString, Map.class);
        for (Map.Entry<String, Object> stringStringEntry : map.entrySet()) {
            String value = stringStringEntry.getValue()+"";
            String key = stringStringEntry.getKey();
            if(!"".equals(value)){
                contentMap.put(key,value);
            }
        }
        commercialTenantDetailsExt.setContentMap(contentMap);
        return commercialTenantDetailsExt;

    }

    /**
     * 商户进件接口调用
     * 1.商户进件
     * 2.上传图片
     * @param commercialTenantDetailsExt
     * @return
     */
    private NewLandMercRegistResponse mercRegistResult(CommercialTenantDetailsExt commercialTenantDetailsExt){
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandMercRegistRequest request = new NewLandMercRegistRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("version","V1.0.1");
        preMap.put("stl_sign", "1");////结算标志
        preMap.put("orgNo",orgNo);//机构号
        preMap.put("stl_oac", commercialTenantDetailsExt.getStlOac());//结算账号
        preMap.put("bnk_acnm", commercialTenantDetailsExt.getBnkAcnm());//户名

        preMap.put("wc_lbnk_no",commercialTenantDetailsExt.getWcLbnkNo());//联行行号
        preMap.put("bus_lic_no", commercialTenantDetailsExt.getBusLicNo());//营业执照号
        preMap.put("bse_lice_nm", commercialTenantDetailsExt.getBseLiceNm());//营业执照名
        preMap.put("crp_nm", commercialTenantDetailsExt.getCrpNm());//法人
        preMap.put("mercAdds", commercialTenantDetailsExt.getMercAdds());//商户地址
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        preMap.put("bus_exp_dt", simpleDateFormat.format(commercialTenantDetailsExt.getBusExpDt()));//营业执照有效期
        preMap.put("crp_id_no", commercialTenantDetailsExt.getCrpIdNo());//法人身份证号
        preMap.put("crp_exp_dt", simpleDateFormat.format(commercialTenantDetailsExt.getCrpExpDt()));//法人身份证有效期

        preMap.put("stoe_nm", commercialTenantDetailsExt.getStoeNm());//门店名
        preMap.put("stoe_cnt_nm", commercialTenantDetailsExt.getStoeCntNm());//门店联系人
        preMap.put("stoe_cnt_tel", commercialTenantDetailsExt.getStoeCntTel());//联系人手机号


        preMap.put("mcc_cd", commercialTenantDetailsExt.getMccCd());//mcc,查询出来
        preMap.put("stoe_area_cod", commercialTenantDetailsExt.getStoeAreaCod());//区域码，查询出来

        preMap.put("stoe_adds", commercialTenantDetailsExt.getStoeAdds()); //门店地址
        preMap.put("trm_rec", commercialTenantDetailsExt.getTrmRec());//终端数量
        preMap.put("mailbox", commercialTenantDetailsExt.getMailbox());//
        preMap.put("alipay_flg",commercialTenantDetailsExt.getAlipayFlg());
        preMap.put("yhkpay_flg",commercialTenantDetailsExt.getYhkpayFlg());
        Map<String,String> bizContentMap = new HashMap<>();
        bizContentMap.putAll(commercialTenantDetailsExt.getContentMap());
        request.setBizContent(bizContentMap);
        request.setPre(preMap);
        NewLandMercRegistResponse response = newLandpayClient.execute(request);
        return response;
    }

    /**
     * mcc查询
     * 1.调用接口，
     * 2.保存进入数据字典中
     * @return
     */
    public ObjectResult mCCSearch(){
        SysDictionary sysDictionary = this.getSysDictionaryByType("3000");
        NewLandMCCSearchResponse response = this.mCCSearchResult();
        if(response != null){
            if(response.isSuccess() && "000000".equals(response.code())){
                if(sysDictionary == null){
                    sysDictionary = new SysDictionary();
                    sysDictionary.setType("3000");
                    sysDictionary.setName("新大陆MCC");
                    List<NewLandMCCSearch> recList = response.getRec();
                    sysDictionary.setValue(JSONObject.toJSONString(recList));
                    sysDictionaryService.add(sysDictionary);
                }else{
                    sysDictionary.setType("3000");
                    sysDictionary.setName("新大陆MCC");
                    List<NewLandMCCSearch> recList = response.getRec();
                    sysDictionary.setValue(JSONObject.toJSONString(recList));
                    sysDictionaryService.update(sysDictionary.getId(),sysDictionary);
                }
                //开启线程进行mcc分类入库操作
                new Thread(()->{
                    this.addCCSearch(response.getRec());
                }).start();
                return new ObjectResult(CommonCode.SUCCESS,sysDictionary);
            }
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * mcc分类入库
     * 此代码影响性能，谨慎执行
     * @param recList
     */
    private void addCCSearch(List<NewLandMCCSearch> recList){
        if(recList == null){
            return;
        }
        long startTime = System.currentTimeMillis();
        LOGGER.info("开始执行："+startTime);
        if(recList == null){
            return;
        }
        //省份添加
        List<Map<String,Object>> supLsit  = new ArrayList<>();
        for (NewLandMCCSearch newLandMCCSearch : recList) {
            int count = 0;
            Map<String,Object> supMap = new HashMap<>();
            String code = newLandMCCSearch.getSupMccCd();
            String name = newLandMCCSearch.getSupMccNm();
            for (Map<String, Object> map : supLsit) {
                if(code.equals(map.get("code"))){
                    count ++;
                    break;
                }
            }
            if(count == 0){
                supMap.put("code",code);
                supMap.put("name",name);
                supLsit.add(supMap);
            }
        }

        //保存进入数据库
        Mcc mccSup = new Mcc();
        mccSup.setCode("0");
        mccSup.setName("一级目录列表");
        mccSup.setValue(JSONObject.toJSONString(supLsit));
        mccSup.setCreateTime(new Date());
        mccRepository.save(mccSup);

        //每个省对应的市添加
        List<Map<String,Object>> mccTypLsit  = null;
        for (Map<String, Object> supMap : supLsit) {
            String supCode = String.valueOf(supMap.get("code"));
            String supName = String.valueOf(supMap.get("name"));
            mccTypLsit  = new ArrayList<>();
            for (NewLandMCCSearch newLandMCCSearch : recList) {
                int count = 0;
                Map<String,Object> typeMap = new HashMap<>();
                String supCode1 = newLandMCCSearch.getSupMccCd();
                String supName1 = newLandMCCSearch.getSupMccNm();
                if(supCode.equals(supCode1)){
                    String mccType1Code = newLandMCCSearch.getMccTyp();
                    String mccType1Name = newLandMCCSearch.getMccTypNm();
                    for (Map<String, Object> map : mccTypLsit) {
                        if(mccType1Code.equals(map.get("code"))){
                            count ++;
                            break;
                        }

                    }
                    if(count == 0){
                        typeMap.put("code",mccType1Code);
                        typeMap.put("name",mccType1Name);
                        mccTypLsit.add(typeMap);
                    }
                }
            }
            //保存进入数据库
            Mcc mccSup1 = new Mcc();
            mccSup1.setCode(supCode);
            mccSup1.setName(supName+":列表");
            mccSup1.setValue(JSONObject.toJSONString(mccTypLsit));
            mccSup1.setCreateTime(new Date());
            mccRepository.save(mccSup1);
            //插入对应的市
            //每个市对应的区添加
            //
            List<Map<String,Object>> mccLsit = null;
            for (Map<String, Object> typeMap : mccTypLsit) {
                mccLsit = new ArrayList<>();
                String  typeCode = String.valueOf(typeMap.get("code"));
                String typeName = String.valueOf(typeMap.get("name"));
                for (NewLandMCCSearch newLandMCCSearch : recList) {
                    String mccType = newLandMCCSearch.getMccTyp();
                    if(mccType.equals(typeCode)){
                        int count = 0;
                        Map<String,Object> areaMap = new HashMap<>();
                        String mccCode = newLandMCCSearch.getMccCd();
                        String mccName = newLandMCCSearch.getMccNm();
                        for (Map<String, Object> map : mccLsit) {
                            String  code = String.valueOf(map.get("code"));
                            if(code.equals(mccCode)){
                                count ++;
                                break;
                            }
                        }
                        if(count == 0){
                            areaMap.put("code",mccCode);
                            areaMap.put("name",mccName);
                            mccLsit.add(areaMap);
                        }
                    }
                }
                //保存进入数据库
                Mcc mccSup2 = new Mcc();
                mccSup2.setCode(typeCode);
                mccSup2.setName(typeName+":列表");
                mccSup2.setValue(JSONObject.toJSONString(mccLsit));
                mccSup2.setCreateTime(new Date());
                mccRepository.save(mccSup2);
            }
        }
        LOGGER.info("mcc插入结束执行，耗时："+(System.currentTimeMillis()-startTime));

    }

    /**
     * 查询商户表，获取图片
     * 1.判断商户是否为空
     * 2.判断图片是否存在
     * 3.图片key与接口中type对应
     * 4.上传成功后，调用提交
     *
     */
    public void findUploadImage(String commercialTenantId,String commercialTenantDetailsId){
        CommercialTenant commercialTenant = this.getCommercialTenantById(commercialTenantId);
        if(commercialTenant == null){

        }
        if(StringUtils.isEmpty(commercialTenant.getImageList())){

        }
        Map<String,String> map = JSONObject.parseObject(commercialTenant.getImageList(), Map.class);
        Map<String,String> map1 = new HashMap<>();
        map1.put("permissionsPictureDoor","6");//门头照
        map1.put("permissionsPictureStore","7");//店内照
        map1.put("permissionsPictureCheckstand","8");//收银台照
        map1.put("permissionsPictureCardPositive","4");//身份证照正
        map1.put("permissionsPictureCardReverse","5");//身份证照反
        map1.put("permissionsPictureHandheld","13");//手持身份证照
        map1.put("permissionsPictureBank","11");//银行卡照
        map1.put("permissionsPictureBusiness","1");//营业执照
        //map1.put("permissionsPictureQualification","");//资质许可证
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            String key = stringStringEntry.getKey();
            this.uploadImageResult(map1.get(key),map.get(key),commercialTenantDetailsId);
        }
        //进行提交
        NewLandMercSubmitResponse response = this.mercSubmitResult(commercialTenantDetailsId);
        CommercialTenantDetails one = this.getCommercialTenantDetailsById(commercialTenantDetailsId);
        if(response !=null){
            if(response.isSuccess() && "000000".equals(response.code())){
                //修改数据库
                one.setStatus(1);
            }else{
                one.setStatus(1);
            }
        }else{
            one.setStatus(1);
        }
        commercialTenantDetailsRepository.save(one);

    }

    /**
     * 上传图片接口调用
     * @param imgTyp
     * @param url
     * @param id
     * @return
     */
    private NewLandUploadImageResponse uploadImageResult(String imgTyp,String url,String id){
        CommercialTenantDetails commercialTenantDetails = this.getCommercialTenantDetailsById(id);
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandUploadImageRequest request = new NewLandUploadImageRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("mercId", commercialTenantDetails.getMercId());//商户号
        preMap.put("orgNo", orgNo);//机构号
        preMap.put("log_no", commercialTenantDetails.getLogNo());//商户修改申请接口/商户进件接口返回的log_no
        preMap.put("stoe_id", commercialTenantDetails.getStoeId());//
        preMap.put("imgTyp",imgTyp);
        //图片名称处理
        String imgName = url.substring(url.lastIndexOf("/") + 1);
        preMap.put("imgNm",imgName);
        Map<String,String> bizContentMap = new HashMap<>();
        String imageHex = this.imageToHex(url);
        bizContentMap.put("imgFile",imageHex);
        request.setPre(preMap);
        request.setBizContent(bizContentMap);
        NewLandUploadImageResponse response = newLandpayClient.execute(request);
        return response;
    }

    /**
     * 商户提交接口
     * @return
     */
    private NewLandMercSubmitResponse mercSubmitResult(String id){
        CommercialTenantDetails commercialTenantDetails = this.getCommercialTenantDetailsById(id);
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandMercSubmitRequest request = new NewLandMercSubmitRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("mercId", commercialTenantDetails.getMercId());//商户号
        preMap.put("orgNo", orgNo);//机构号
        preMap.put("log_no", commercialTenantDetails.getLogNo());//商户修改申请接口/商户进件接口返回的log_no
        preMap.put("version","V1.0.1");
        Map<String,String> bizContentMap = new HashMap<>();
        request.setPre(preMap);
        request.setBizContent(bizContentMap);
        NewLandMercSubmitResponse response = newLandpayClient.execute(request);
        return response;
    }

    /**
     * 商户状态查询
     * @param id
     * @return
     */
    public ObjectResult mercSearch(String id){
        NewLandMercSearchResponse response = this.mercSearchResult(id);
        CommercialTenantDetails one = this.getCommercialTenantDetailsById(id);
        if(response !=null){
            if(response.isSuccess() && "000000".equals(response.code())){
                if("1".equals(response.getCheckFlag())){
                    //通过
                    one.setStatus(2);
                }
                if("2".equals(response.getCheckFlag())){
                    //驳回
                    one.setStatus(3);
                }
                if("3".equals(response.getCheckFlag())){
                    //通过
                    one.setStatus(1);
                }
                commercialTenantDetailsRepository.save(one);
                return new ObjectResult(CommonCode.SUCCESS,null);

            }else{
                one.setStatus(5);
            }
        }else{
            one.setStatus(5);
        }

        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * 商户状态查询接口
     * @return
     */
    private NewLandMercSearchResponse mercSearchResult(String id){
        CommercialTenantDetails commercialTenantDetails = this.getCommercialTenantDetailsById(id);
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandMCCSearchRequest request = new NewLandMCCSearchRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("mercId",commercialTenantDetails.getMercId());
        preMap.put("version","V1.0.1");
        preMap.put("orgNo",orgNo);
        Map<String,String> bizContentMap = new HashMap<>();
        request.setPre(preMap);
        request.setBizContent(bizContentMap);
        NewLandMercSearchResponse response = newLandpayClient.execute(request);
        return response;
    }







    /**
     * mcc接口调用
     * @return
     */
    private NewLandMCCSearchResponse mCCSearchResult(){
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandMCCSearchRequest request = new NewLandMCCSearchRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("orgNo",orgNo);
        preMap.put("version","V1.0.1");
        Map<String,String> bizContentMap = new HashMap<>();
        request.setPre(preMap);
        request.setBizContent(bizContentMap);
        NewLandMCCSearchResponse response = newLandpayClient.execute(request);
        return response;
    }

    /**
     * 区域码查询
     * @return
     */
    public ObjectResult areaCode(){
        SysDictionary sysDictionary = this.getSysDictionaryByType("4000");
        NewLandAreaCodeResponse response = this.areaCodeResult();
        if(response != null){
            if(response.isSuccess() && "000000".equals(response.code())){
                if(sysDictionary == null){
                    sysDictionary = new SysDictionary();
                    sysDictionary.setType("4000");
                    sysDictionary.setName("新大陆区域码");
                    List<NewLandAreaCode> recList = response.getRec();
                    sysDictionary.setValue(JSONObject.toJSONString(recList));
                    sysDictionaryService.add(sysDictionary);
                }else{
                    sysDictionary.setType("4000");
                    sysDictionary.setName("新大陆区域码");
                    List<NewLandAreaCode> recList = response.getRec();
                    sysDictionary.setValue(JSONObject.toJSONString(recList));
                    sysDictionaryService.update(sysDictionary.getId(),sysDictionary);
                }
                //开启线程进行省市区插入
                new Thread(()->{
                   this.addArea(response.getRec());
                }).start();
                return new ObjectResult(CommonCode.SUCCESS,sysDictionary);
            }
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * areaCode接口调用
     * @return
     */
    private NewLandAreaCodeResponse areaCodeResult(){
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        NewLandAreaCodeRequest request = new NewLandAreaCodeRequest();
        Map<String,String> preMap = new HashMap<>();
        preMap.put("orgNo",orgNo);
        preMap.put("version","V1.0.1");
        Map<String,String> bizContentMap = new HashMap<>();
        request.setPre(preMap);
        request.setBizContent(bizContentMap);
        NewLandAreaCodeResponse response = newLandpayClient.execute(request);
        return response;
    }

    /**
     * 此代码很影响性能，谨慎执行
     * @param recList
     */
    private void addArea(List<NewLandAreaCode> recList){
        long startTime = System.currentTimeMillis();
        LOGGER.info("开始执行："+startTime);
        if(recList == null){
            return;
        }
        //省份添加
        List<Map<String,Object>> provLsit  = new ArrayList<>();
        for (NewLandAreaCode newLandAreaCode : recList) {
            int count = 0;
            Map<String,Object> provMap = new HashMap<>();
            String code = newLandAreaCode.getMercProv();
            String name = newLandAreaCode.getProvNm();
            for (Map<String, Object> map : provLsit) {
                if(code.equals(map.get("code"))){
                    count ++;
                    break;
                }
            }
            if(count == 0){
                provMap.put("code",code);
                provMap.put("name",name);
                provLsit.add(provMap);
            }
        }

        //保存进入数据库
        Area areaProv = new Area();
        areaProv.setCode("1");
        areaProv.setName("省份列表");
        areaProv.setValue(JSONObject.toJSONString(provLsit));
        areaProv.setCreateTime(new Date());
        areaRepository.save(areaProv);

        //每个省对应的市添加
        List<Map<String,Object>> cityLsit  = null;
        for (Map<String, Object> provMap : provLsit) {
            String provCode = String.valueOf(provMap.get("code"));
            String provName = String.valueOf(provMap.get("name"));
            cityLsit  = new ArrayList<>();
            for (NewLandAreaCode newLandAreaCode : recList) {
                int count = 0;
                Map<String,Object> cityMap = new HashMap<>();
                String provCode1 = newLandAreaCode.getMercProv();
                String provName1 = newLandAreaCode.getProvNm();
                if(provCode.equals(provCode1)){
                    String mercCityCode = newLandAreaCode.getMercCity();
                    String cityName = newLandAreaCode.getCityNm();
                    for (Map<String, Object> map : cityLsit) {
                        if(mercCityCode.equals(map.get("code"))){
                            count ++;
                            break;
                        }

                    }
                    if(count == 0){
                        cityMap.put("code",mercCityCode);
                        cityMap.put("name",cityName);
                        cityLsit.add(cityMap);
                    }
                }
            }
            //保存进入数据库
            Area areaProv1 = new Area();
            areaProv1.setCode(provCode);
            areaProv1.setName(provName+":市列表");
            areaProv1.setValue(JSONObject.toJSONString(cityLsit));
            areaProv1.setCreateTime(new Date());
            areaRepository.save(areaProv1);
            //插入对应的市
            //每个市对应的区添加
            //
            List<Map<String,Object>> areaLsit = null;
            for (Map<String, Object> cityMap : cityLsit) {
                areaLsit = new ArrayList<>();
                String  cityCode = String.valueOf(cityMap.get("code"));
                String cityName = String.valueOf(cityMap.get("name"));
                for (NewLandAreaCode newLandAreaCode : recList) {
                    String mercCity = newLandAreaCode.getMercCity();
                    if(mercCity.equals(cityCode)){
                        int count = 0;
                        Map<String,Object> areaMap = new HashMap<>();
                        String areaCode = newLandAreaCode.getMercArea();
                        String areaName = newLandAreaCode.getAreaNm();
                        for (Map<String, Object> map : areaLsit) {
                            String  code = String.valueOf(map.get("code"));
                            if(code.equals(areaCode)){
                                count ++;
                                break;
                            }
                        }
                        if(count == 0){
                            areaMap.put("code",areaCode);
                            areaMap.put("name",areaName);
                            areaLsit.add(areaMap);
                        }
                    }
                }
                //保存进入数据库
                Area areaProv2 = new Area();
                areaProv2.setCode(cityCode);
                areaProv2.setName(cityName+":区列表");
                areaProv2.setValue(JSONObject.toJSONString(areaLsit));
                areaProv2.setCreateTime(new Date());
                areaRepository.save(areaProv2);
            }
        }
        LOGGER.info("省市区插入结束执行，耗时："+(System.currentTimeMillis()-startTime));

    }

    /**
     * 根据mccCode查询对应的类型
     * @param code
     * @return
     */
    public ObjectResult findMccByCode(String code){
        Mcc mcc = mccRepository.findByCode(code);
        List list = JSONObject.parseObject(mcc.getValue(), List.class);
        return new ObjectResult(CommonCode.SUCCESS,list);
    }

    /**
     * 依据省市区code查询对应的省，市，区
     * @param code
     * @return
     */
    public ObjectResult findPcaByCode(String code){
        Area area = areaRepository.findByCode(code);
        List list = JSONObject.parseObject(area.getValue(), List.class);
        return new ObjectResult(CommonCode.SUCCESS,list);
    }



    /**
     * 根据type查找数据字典
     * @param type
     * @return
     */
    private SysDictionary getSysDictionaryByType(String type){
        ObjectResult sysDictionaryResult = sysDictionaryService.findByType(type);
        boolean success = sysDictionaryResult.isSuccess();
        if(success){
            String sysDictionaryJson = JSONObject.toJSONString(sysDictionaryResult.getObject());
            SysDictionary sysDictionary1 = JSONObject.parseObject(sysDictionaryJson, SysDictionary.class);
            return sysDictionary1;
        }
        return null;
    }

    /**
     * 根据id查找商户表
     * @param id
     * @return
     */
    private CommercialTenant getCommercialTenantById(String id){
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 根据id查找商户详情表
     * @param id
     * @return
     */
    private CommercialTenantDetails getCommercialTenantDetailsById(String id){
        Optional<CommercialTenantDetails> optional = commercialTenantDetailsRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    private   String imageToHex(String url){
        try {
            InputStream inputStream = GetImgUrlUtil.getImageStream(url);
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            byte[] buff=new byte[1024];
            int len=0;
            while((len=inputStream.read(buff))!=-1){
                bos.write(buff,0,len);
            }
            byte[] result=bos.toByteArray();
            return bytesToHexString(result);
        } catch (IOException e) {
            LOGGER.error("图片获取转换io错误{}",e.getMessage());
        }
        return null;
    }

    private  String bytesToHexString(byte[] src){

        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();

    }



}
